using System;

namespace Behaving.Actions
{
    public class ActionBehaviour : Behaviour
    {
        private readonly Action _action;
        private readonly Func<RunningState> _runningStateAction;
        private Func<bool> _predicate;

        public ActionBehaviour(Action action, Action start = null, Action stop = null)
        {
            _action = action;
            StopAction = stop;
            StartAction = start;
        }

        public ActionBehaviour(Func<bool> predicate, Action action, Action start = null, Action stop = null)
            : this(action, start, stop)
        {
            _predicate = predicate;
        }

        public ActionBehaviour(Func<RunningState> runningStateAction, Action start = null, Action stop = null)
        {
            _runningStateAction = runningStateAction;
            StopAction = stop;
            StartAction = start;
        }

        public ActionBehaviour SetPredicate(Func<bool> predicate)
        {
            _predicate = predicate;
            return this;
        }

        public override RunningState Execute(BehaviourTree behaviourTree)
        {
            if (_action != null && (_predicate == null || _predicate()))
            {
                _action();
                return RunningState.Success;
            }

            if (_runningStateAction != null)
            {
                return _runningStateAction();
            }
            else
            {
                return RunningState.Failure;
            }
        }
    }
}